package com.zz.kt.order.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.zz.client.activity.CouponInfoFeignClient;
import com.zz.kt.client.course.CourseFeignClient;
import com.zz.kt.client.user.UserInfoFeignClient;
import com.zz.kt.exception.KtException;
import com.zz.kt.model.activity.CouponInfo;
import com.zz.kt.model.base.BaseEntity;
import com.zz.kt.model.order.OrderDetail;
import com.zz.kt.model.order.OrderInfo;
import com.zz.kt.model.user.UserInfo;
import com.zz.kt.model.vod.Course;
import com.zz.kt.order.mapper.OrderDetailMapper;
import com.zz.kt.order.mapper.OrderInfoMapper;
import com.zz.kt.order.service.OrderDetailService;
import com.zz.kt.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zz.kt.utils.AuthContextHolder;
import com.zz.kt.utils.OrderNoUtils;
import com.zz.kt.vo.order.OrderFormVo;
import com.zz.kt.vo.order.OrderInfoQueryVo;
import com.zz.kt.vo.order.OrderInfoVo;
import com.zz.kt.vo.vod.CourseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 订单表 订单表 服务实现类
 * </p>
 *
 * @author zz
 * @since 2022-09-05
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private CourseFeignClient courseFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private CouponInfoFeignClient couponInfoFeignClient;

    //生成订单方法
    @Override
    public Long submitOrder(OrderFormVo orderFormVo) {
        //1 获取生成订单条件值
        Long courseId = orderFormVo.getCourseId();
        Long couponId = orderFormVo.getCouponId();
        Long userId = AuthContextHolder.getUserId();

        System.out.println("couponId:______________"+couponId);
        System.out.println("userId:______________"+userId);

        //2 判断当前用户,针对当前课程是否已经生成订单
        // 课程id，用户id
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getCourseId,courseId);
        wrapper.eq(OrderDetail::getUserId, userId);
        OrderDetail orderDetailExist = orderDetailService.getOne(wrapper);

        if (orderDetailExist != null){
            try {
                OrderInfo orderInfo = new OrderInfo();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(new Date());
                Date date = sdf.parse(format);

                orderInfo.setUpdateTime(date);//更新订单更新时间
                orderInfo.setId(orderDetailExist.getId());
                baseMapper.updateById(orderInfo);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            return orderDetailExist.getId();//订单已经存在，直接返回订单id
        }

        //3 根据课程id查询课程信息
        Course course = courseFeignClient.getById(courseId);
        if (course == null) {
            throw new KtException(20001,"课程不存在");
        }

        //4 根据用户id查询用户信息
        UserInfo userInfo = userInfoFeignClient.getById(userId);
        if (userInfo == null) {
            throw new KtException(20001,"用户不存在");
        }

        //5 根据优惠卷id查询优惠卷信息
        BigDecimal couponReduce = new BigDecimal(0);
        if (couponId != null) {
            CouponInfo couponInfo = couponInfoFeignClient.getById(couponId);
            couponReduce = couponInfo.getAmount();
        }

        //6 封装订单生成需要的数据到对象中，完成添加订单
        //6.1 封装数据到OrderInfo对象里面，添加订单基本信息表
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userInfo.getNickName());
        orderInfo.setPhone(userInfo.getPhone());
        orderInfo.setProvince(userInfo.getProvince());
        orderInfo.setOriginAmount(course.getPrice());
        orderInfo.setCouponReduce(couponReduce.divide(BigDecimal.valueOf(100)));
        orderInfo.setFinalAmount(orderInfo.getOriginAmount().subtract(orderInfo.getCouponReduce()));
        orderInfo.setOutTradeNo(OrderNoUtils.getOrderNo());
        orderInfo.setTradeBody(course.getTitle());
        orderInfo.setOrderStatus("0");

        baseMapper.insert(orderInfo);

        //6.2 封装数据到OrderDetail对象里面，添加订单详情信息表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orderInfo.getId());
        orderDetail.setUserId(userId);
        orderDetail.setCourseId(courseId);
        orderDetail.setCourseName(course.getTitle());
        orderDetail.setCover(course.getCover());
        orderDetail.setOriginAmount(course.getPrice());
        orderDetail.setCouponReduce(couponReduce.divide(BigDecimal.valueOf(100)));
        orderDetail.setFinalAmount(orderInfo.getOriginAmount().subtract(orderInfo.getCouponReduce()));
        orderDetailService.save(orderDetail);

        //7 更新优惠卷状态
        if(null != orderFormVo.getCouponUseId()) {
            couponInfoFeignClient.updateCouponInfoUseStatus(orderFormVo.getCouponUseId(), orderInfo.getId());
        }

        //8 返回订单id
        return orderInfo.getId();
    }

    //根据订单id获取订单信息
    @Override
    public OrderInfoVo getOrderInfoVoById(Long id) {
        //id查询订单基本信息和详情信息
        OrderInfo orderInfo = baseMapper.selectById(id);
        OrderDetail orderDetail = orderDetailService.getById(id);
        //封装OrderInfoVo
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        BeanUtils.copyProperties(orderInfo, orderInfoVo);
        orderInfoVo.setCourseId(orderDetail.getCourseId());
        orderInfoVo.setCourseName(orderDetail.getCourseName());
        return orderInfoVo;
    }

    //更新订单状态：已经支付
    @Override
    public void updateOrderStatus(String out_trade_no) {
        //根据订单号查询订单
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getOutTradeNo,out_trade_no);
        OrderInfo orderInfo = baseMapper.selectOne(wrapper);
        //设置订单状态
        orderInfo.setOrderStatus("1");
        //支付时间
        try {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(date);
            Date dateR = sdf.parse(format);
            orderInfo.setPayTime(dateR);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        //调用方法更新
        baseMapper.updateById(orderInfo);

        //OrderDetail
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orderInfo.getId());
        orderDetail.setUpdateTime(orderInfo.getUpdateTime());
        orderDetailService.updateById(orderDetail);
    }

    //查询是否购买课程
    @Override
    public Boolean selectStatus(Long userId, Long courseId) {
        Boolean status = baseMapper.selectStatus(userId,courseId);
        return status;
    }

    //订单列表(根据用户id
    @Override
    public List selectOrderInfoPageByUserId() {
        //获取当前userId
        Long userId = AuthContextHolder.getUserId();

        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getUserId,userId);

        //调用条件
        List<OrderInfo> records = baseMapper.selectList(wrapper);

        for (OrderInfo record : records) {
            System.out.println("___________"+record);
        }

        //订单里面包含详情内容，封装详情数据，根据订单id查询详情
        records.stream().forEach(item ->{
            this.getOrderDetail(item);
        });

        return records;
    }

    //根据userId查询已购的课程列表
    @Override
    public List selectCourseInfoByUserId() {
        //获取当前userId
        Long userId = AuthContextHolder.getUserId();

        //根据id查询已购课程
        LambdaQueryWrapper<OrderInfo> InfoWrapper = new LambdaQueryWrapper<>();
        InfoWrapper.eq(OrderInfo::getOrderStatus,1);//已购
        InfoWrapper.eq(OrderInfo::getUserId,userId);//当前userId
        List<OrderInfo> orderInfoList = baseMapper.selectList(InfoWrapper);

        //封装OrderInfo---》OrderInfoVo
        List<OrderInfoVo> orderInfoVoList = new ArrayList<>();

        orderInfoList.stream().forEach(orderInfo -> {
            OrderInfoVo orderInfoVo = new OrderInfoVo();
            BeanUtils.copyProperties(orderInfo,orderInfoVo);
            orderInfoVoList.add(orderInfoVo);
        });

        //遍历orderInfoVoList
        orderInfoVoList.stream().forEach(orderInfoVo -> {
            //根据订单id查询orderDetail的信息
            LambdaQueryWrapper<OrderDetail> DetailWrapper = new LambdaQueryWrapper<>();
            DetailWrapper.eq(BaseEntity::getId,orderInfoVo.getId());
            OrderDetail orderDetail = orderDetailService.getOne(DetailWrapper);

            //根据课程id查询课程信息
            Course course = courseFeignClient.getById(orderDetail.getCourseId());

            orderInfoVo.getParam().put("cover",course.getCover());
            orderInfoVo.getParam().put("courseId",course.getId());
        });

        for (OrderInfoVo orderInfoVo : orderInfoVoList) {
            System.out.println("orderInfoVo++++++++++++++"+orderInfoVo);
        }

        return orderInfoVoList;
    }

    //订单列表
    @Override
    public Map<String, Object> selectOrderInfoPage(Page<OrderInfo> pageParam, OrderInfoQueryVo orderInfoQueryVo) {
        //orderInfoQueryVo获取查询条件
        Long userId = orderInfoQueryVo.getUserId();
        String outTradeNo = orderInfoQueryVo.getOutTradeNo();
        String phone = orderInfoQueryVo.getPhone();
        String createTimeEnd = orderInfoQueryVo.getCreateTimeEnd();
        String createTimeBegin = orderInfoQueryVo.getCreateTimeBegin();
        Integer orderStatus = orderInfoQueryVo.getOrderStatus();

        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();

        //判断条件值是否为空，不为空，进行条件封装
        if (!StringUtils.isEmpty(orderStatus)){
            wrapper.eq("order_status",orderStatus);
        }
        if (!StringUtils.isEmpty(userId)){
            wrapper.eq("user_id",userId);
        }
        if(!StringUtils.isEmpty(outTradeNo)) {
            wrapper.eq("out_trade_no",outTradeNo);
        }
        if(!StringUtils.isEmpty(phone)) {
            wrapper.eq("phone",phone);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("update_time",createTimeEnd);
        }

        //调用条件
        Page<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        long total = pages.getTotal();
        long pageCount = pages.getPages();
        List<OrderInfo> records = pages.getRecords();

        //订单里面包含详情内容，封装详情数据，根据订单id查询详情
        records.stream().forEach(item ->{
            this.getOrderDetail(item);
        });

        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("pageCount",pageCount);
        map.put("records",records);

        return map;
    }

    //查询订单详情数据
    private OrderInfo getOrderDetail(OrderInfo orderInfo) {
        //订单id
        Long id = orderInfo.getId();
        //查询订单详情
        OrderDetail orderDetail = orderDetailService.getById(id);
        if (orderDetail != null){
            //Long courseId = orderDetail.getCourseId();
            String courseName = orderDetail.getCourseName();
            Long courseId = orderDetail.getCourseId();
            orderInfo.getParam().put("courseId",courseId);
            orderInfo.getParam().put("courseName",courseName);
        }
        return orderInfo;
    }
}
